package com.zx.mobile.service.proxy;

import com.kspay.AESUtil;
import com.kspay.DateUtil;
import com.kspay.MD5Util;
import com.yeepay.paymobile.utils.PaymobileUtils;
import com.zx.map.dao.model.OrdLog;
import com.zx.map.service.domain.nocard.NocardPayReturnDomain;
import com.zx.map.service.model.OrdLogModel;
import com.zx.map.utils.SUConstants;
import com.zx.mobile.MobileCommonHelper;
import com.zx.mobile.domain.MobileUserDomain;
import com.zx.mobile.domain.NocardCommonPayDomain;
import com.zx.mobile.domain.NocardConfirmPayDomain;
import com.zx.mobile.domain.nocard.MobaoPrePayResponse;
import com.zx.platform.utils.DateUtils;
import com.zx.platform.utils.HttpParamsUtils;
import com.zx.platform.utils.StrUtils;
import com.zx.scp.utils.PropertyUtil;
import org.apache.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;

public class NocardPayProxy {
	private static Logger log = Logger.getLogger(NocardPayProxy.class);

	/**
	 * 摩宝无卡收款 模型转换
	 *
	 * @param user
	 * @param nocardModel
	 * @return
	 */
	public static OrdLogModel transformToOrdLog(NocardCommonPayDomain nocardModel, MobileUserDomain user) {
		// 保存订单信息
		OrdLogModel ordLogModel = new OrdLogModel();
		ordLogModel.setAgentId(user.getMerchantInfoDetailModel().getAgentId());
		ordLogModel.setAgentSysAccount(user.getMerchantInfoDetailModel()
				.getAgentSysAccount());
		ordLogModel.setCreateDate(new Date());
		ordLogModel.setMerchantId(user.getMerchantInfoDetailModel()
				.getMerchantId());
		ordLogModel.setMerSysAccount(user.getMerchantInfoDetailModel()
				.getSysAccount());

		ordLogModel.setTransType(SUConstants.TRANSTYPE_NOCARDINCOME);//无卡收款
		ordLogModel.setPaymentAmt(Double.valueOf(nocardModel.getAmount()));
		ordLogModel.setTransStatus(MobileCommonHelper.OUTCOMESTATUS_NORMAL);
		//增加无卡收款其他信息
		ordLogModel.setBankAccount(nocardModel.getCardByNo());
		ordLogModel.setBankName(nocardModel.getCardByName());
		ordLogModel.setIdentityNo(nocardModel.getCerNumber());
		ordLogModel.setPaymentType(nocardModel.getPayType());//支付方式
		ordLogModel.setValidThru(nocardModel.getExpireDate());
		ordLogModel.setCvv2(nocardModel.getCvv2());
		ordLogModel.setDebitFlag(nocardModel.getCardType());
		return ordLogModel;
	}

	/**
	 * 模型转换
	 *
	 * @param user
	 * @param nocardModel
	 * @return
	 */
	public static OrdLogModel transformToOrdLog(NocardConfirmPayDomain nocardModel, MobileUserDomain user) {
		// 保存订单信息
		OrdLogModel ordLogModel = new OrdLogModel();
		ordLogModel.setAgentId(user.getMerchantInfoDetailModel().getAgentId());
		ordLogModel.setAgentSysAccount(user.getMerchantInfoDetailModel()
				.getAgentSysAccount());
		ordLogModel.setCreateDate(new Date());
		ordLogModel.setMerchantId(user.getMerchantInfoDetailModel()
				.getMerchantId());
		ordLogModel.setMerSysAccount(user.getMerchantInfoDetailModel()
				.getSysAccount());
		ordLogModel.setTransType(SUConstants.TRANSTYPE_NOCARDINCOME);//无卡收款
		ordLogModel.setTransStatus(MobileCommonHelper.OUTCOMESTATUS_NORMAL);
		//增加无卡收款其他信息
		ordLogModel.setBankAccount(nocardModel.getCardNo());
		ordLogModel.setBankName(nocardModel.getOwner());
		ordLogModel.setIdentityNo(nocardModel.getIdCard());
		return ordLogModel;
	}

	/**
	 * 获取无卡支付web链接
	 *
	 * @param payDomain
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String getNoCardPayUrl(NocardConfirmPayDomain payDomain) throws UnsupportedEncodingException {
		int amount = new BigDecimal(payDomain.getAmount()).multiply(
				new BigDecimal("100")).intValue();
		TreeMap<String, Object> map = new TreeMap<String, Object>();
		map.put("orderid", payDomain.getOrderId());
		map.put("transtime", System.currentTimeMillis() / 1000);
		map.put("amount", amount);//以分为单位
		map.put("productcatalog", "21");
		map.put("productname", "宝数钱包-收款");
		map.put("identityid", payDomain.getOrderId());
		map.put("identitytype", 6); //用户标识类型 i
		map.put("terminaltype", 3);
		;//终端标识类型 int √ 0、IMEI；1、MAC；2、UUID；3、OTHER
		map.put("terminalid", payDomain.getOrderId());
		map.put("userip", "192.168.1.121");
		;//用户ip地址
		map.put("cardno", payDomain.getCardNo());
		map.put("idcardtype", "01");
		;// 证件类型 string 非必填 01：身份证，当前只支持身份证
		map.put("idcard", payDomain.getIdCard());
		map.put("owner", payDomain.getOwner());
		map.put("callbackurl", PropertyUtil.getValue("callBackUrl"));   // 页面回调地址 string        非必填
		map.put("fcallbackurl", PropertyUtil.getValue("frontCallBackUrl")); // 后台回调地址 string 非必填
		//第一步 生成AESkey及encryptkey
		String AESKey = PaymobileUtils.buildAESKey();
		String encryptkey = PaymobileUtils.buildEncyptkey(AESKey);
		//第二步 生成data
		String data = PaymobileUtils.buildData(map, AESKey);
		//第三步 获取商户编号及请求地址，并组装支付链接
		String merchantaccount = PaymobileUtils.getMerchantaccount();
		String url = PaymobileUtils.getRequestUrl(PaymobileUtils.PAYAPI_NAME);
		return url + "?merchantaccount=" + URLEncoder.encode(merchantaccount, "UTF-8")
				+ "&data=" + URLEncoder.encode(data, "UTF-8")
				+ "&encryptkey=" + URLEncoder.encode(encryptkey, "UTF-8");
	}

	/**
	 * 获取摩宝预支付接口
	 *
	 * @param nocardCommonPayDomain
	 * @return
	 */
	public static String getMobaoPrePayUrl(NocardCommonPayDomain nocardCommonPayDomain, String orderId) throws Exception {
		Map<String, String> transmap = new LinkedHashMap<String, String>();
		transmap.put("versionId", "001");     //版本号  固定
		transmap.put("businessType", "1401");  //预交易  1401
		transmap.put("insCode","");
		transmap.put("merId", PropertyUtil.getValue("mobao_merId"));            //商户号
		transmap.put("orderId", orderId);   //订单号
		transmap.put("transDate", DateUtils.dateToString(new Date(), DateUtils.DATE_TIME_FMT_OTHER));  //时间    yymmddhhmmss
		transmap.put("transAmount", nocardCommonPayDomain.getAmount());   //金额 单位元
		transmap.put("cardByName", MD5Util.encode(nocardCommonPayDomain.getCardByName().getBytes("UTF-8")));  //此处的MD5util为Base64加密
		transmap.put("cardByNo", nocardCommonPayDomain.getCardByNo());  //卡号
		transmap.put("cardType", nocardCommonPayDomain.getCardType());  //卡类型
		if(StrUtils.isNotBlank(nocardCommonPayDomain.getExpireDate())) {
			transmap.put("expireDate", nocardCommonPayDomain.getExpireDate().substring(2) + nocardCommonPayDomain.getExpireDate().substring(0, 2)); // 有效期
		}
		transmap.put("CVV", nocardCommonPayDomain.getCvv2());    //CVN
		transmap.put("bankCode", "");   //可为空    银行代码
		transmap.put("openBankName", "");//可为空    银行代码
		transmap.put("cerType", "00");   //证件类型  固定00  身份证
		transmap.put("cerNumber", nocardCommonPayDomain.getCerNumber());//身份证
		transmap.put("mobile", nocardCommonPayDomain.getMobile());  //手机号
		transmap.put("isAcceptYzm", "00"); //短信验证 默认00
		transmap.put("orderDesc", MD5Util.encode("宝数金融无卡支付".getBytes("UTF-8")));
		transmap.put("instalTransFlag", "01");  //分期标志 01不分期
		return PropertyUtil.getValue("mobao_prepay_url")+getMobaoEncodeUrl(transmap);
	}



	/**
	 * 摩宝验证码验证
	 *
	 * @param mobaoPrePayResponse
	 * @return
	 */
	public static String getMobaoCheckSmsUrl(MobaoPrePayResponse mobaoPrePayResponse) {
		Map<String, String> transmap = new LinkedHashMap<String, String>();
		transmap.put("versionId", "001");
		transmap.put("businessType", "1411");
		transmap.put("insCode", "");
		transmap.put("merId", PropertyUtil.getValue("mobao_merId"));
		transmap.put("yzm",mobaoPrePayResponse.getYzm());
		transmap.put("ksPayOrderId", mobaoPrePayResponse.getKsPayOrderId());

		return PropertyUtil.getValue("mobao_checksms_url")+getMobaoEncodeUrl(transmap);
	}

	/**
	 * 更改订单状态或通知查询订单 拼接url参数   status    amount    orderid  必填
	 *
	 * @param nocardPayReturnDomain
	 * @param ordLogModel
	 * @return
	 */
	public static String getOrderNotifyPayUrl(NocardPayReturnDomain nocardPayReturnDomain, OrdLogModel ordLogModel) {
		String url;
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append("orderId=").append(ordLogModel.getOrdId()).append("&");
		stringBuilder.append("amount=").append(ordLogModel.getPaymentAmt()).append("&");
		stringBuilder.append("status=").append(nocardPayReturnDomain.getStatus()).append("&");
		stringBuilder.append("ybOrderId=").append(nocardPayReturnDomain.getYbOrderId());

		if (nocardPayReturnDomain.getStatus().equalsIgnoreCase("F") || nocardPayReturnDomain.getStatus().equalsIgnoreCase("S")) {
			url = PropertyUtil.getValue("order_notifypay_url");
		} else {
			url = PropertyUtil.getValue("order_checkPayStatus_url");
		}
		return url + stringBuilder.toString();
	}

	/**
	 * 查询摩宝订单状态
	 * @param ordLogTmp
	 * @return
	 */
	public static String getMobaoQueryStatusUrl(OrdLog ordLogTmp) {
		Map<String,String>  transmap= new LinkedHashMap<String, String>();
		transmap.put("versionId","001");
		transmap.put("businessType","1421");
		transmap.put("insCode","");
		transmap.put("merId", PropertyUtil.getValue("mobao_merId"));
		transmap.put("orderId",ordLogTmp.getOrdId());
		transmap.put("transDate",DateUtils.dateToString(new Date(),DateUtils.DATE_TIME_FMT_OTHER));
		//transmap.put("transDate",DateUtil.getTimess1());
		//需要加密的字符串
		return PropertyUtil.getValue("mobao_querystatus_url")+getMobaoEncodeUrl(transmap);
	}

	private static String getMobaoEncodeUrl(Map<String, String> transmap) {
		String signstr = HttpParamsUtils.buildPayParams(transmap);
		log.debug("摩宝支付需要签名的明文:" + signstr);
		String signtrue = MD5Util.MD5Encode(signstr + PropertyUtil.getValue("mobao_merkey"));
		transmap.put("signType", "MD5");
		transmap.put("signData", signtrue);
		//AES加密
		String transData = HttpParamsUtils.buildPayParams(transmap);
		log.debug("摩宝aes加密前："+transData);
		transData = AESUtil.encrypt(transData, PropertyUtil.getValue("mobao_merkey"));
		log.debug("摩宝加密数据："+transData);

		String testUrl = "merId=" + PropertyUtil.getValue("mobao_merId")
				+ "&transData=" + transData;
		log.debug("摩宝url:"+testUrl);
		return testUrl;
	}

}
